package com.ft.scan.controller;

import com.ft.scan.DTO.RequestDTO;
import com.ft.scan.DTO.WechatRequestDTO;
import com.ft.scan.common.AliOSSUtils;
import com.ft.scan.common.Result;
import com.ft.scan.common.WxResult;
import com.ft.scan.domain.User;
import com.ft.scan.service.IMobileService;
import com.ft.scan.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;

@RestController
@RequestMapping("/ft/user")
@Api(tags = "用户管理接口")
public class UserController {


    @Autowired
    private IUserService userService;


    @Autowired
    private IMobileService mobileService;

    @ApiOperation(value = "用户名密码登录")
    @GetMapping("/login-username")
    public Result loginByUsernameAndPassword(
            @ApiParam(name = "username", value = "用户名") String username,
            @ApiParam(name = "password", value = "用户密码") String password) {
        User user = userService.selectUserByUsernameAndPassword(username, password);
        if (user != null) {
            return Result.ok(user);
        } else {
            return Result.fail("用户名或密码错误");
        }
    }

    @ApiOperation(value = "微信登录")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = WechatRequestDTO.class)
    @PostMapping("/login-wechat")
    public Result loginByOpenid(@RequestBody WechatRequestDTO request) {
        String code = request.getCode();
        String avatarData = request.getAvatarData();
        String nickName = request.getNickName();
        WxResult wxResult = userService.getOpenIdByCode(code);
        if (wxResult == null) {
            return Result.fail(66, "无法获取用户信息");
        } else if (wxResult.getCode() != 200) {
            return Result.fail(wxResult.getCode(), wxResult.getMessage());
        }
        byte[] avatarBytes = null;
        try {
            avatarBytes = Base64.getDecoder().decode(avatarData);
        } catch (Exception e) {
            return Result.fail("图片数据格式不正确");
        }
        String openId = wxResult.getOpenid();
        User user = userService.selectUserByOpenid(openId);
        if (user != null) {
            return Result.ok(user);
        } else {
            String avatarUrl = AliOSSUtils.uploadFileToOSS("avatar-" + openId + ".jpg", avatarBytes);
            return userService.insertUserByOpenID(openId, nickName, avatarUrl) == 1 ?
                    Result.ok(userService.selectUserByOpenid(openId)) :
                    Result.fail("微信登录失败");
        }
    }


    @ApiOperation(value = "手机号登录（发送验证码）", notes = "步骤1，发送验证码")
    @GetMapping("/login-mobile-send")
    public Result loginByMobileSend(
            @ApiParam(name = "mobile", value = "手机号", required = true) String mobile) {
        if (StringUtils.isNotBlank(mobile)) {
            if (mobileService.sendNote(mobile)) {
                return Result.ok("短信发送成功，10分钟内有效");
            } else {
                return Result.fail("验证码发送失败");
            }
        } else {
            return Result.fail("无效的登录参数");
        }
    }


    @ApiOperation(value = "手机号登录（校验验证码）", notes = "步骤2,，验证失败会返回201状态码")
    @GetMapping("/login-mobile-verify")
    public Result loginByMobileVerify(
            @ApiParam(name = "mobile", value = "手机号", required = true) String mobile,
            @ApiParam(name = "code", value = "验证码", required = true) String code) {
        if (StringUtils.isNotBlank(mobile) && StringUtils.isNotBlank(code)) {
            String codeInRedis = mobileService.selectNoteByMobile(mobile);
            if (!codeInRedis.isEmpty() && codeInRedis.equals(code)) {
                User user = userService.selectUserByMobile(mobile);
                // 如果没注册就先注册，如果注册了就直接登录
                if (user == null && userService.insertUserByMobile(mobile) == 1) {
                    user = userService.selectUserByMobile(mobile);
                }
                return Result.ok(user);
            } else {
                return Result.fail(201, "验证码错误，请重试");
            }
        } else {
            return Result.fail("无效的参数");
        }
    }


    @ApiOperation(value = "注册（用户名、密码）", notes = "使用用户名和密码登录")
    @PostMapping("/register-username")
    public Result registerByUsername(
            @ApiParam(name = "username", value = "用户名", required = true) String username,
            @ApiParam(name = "password", value = "密码", required = true) String password) {
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            if (!userService.selectUserByUsername(username).isEmpty()) {
                return Result.fail("用户名已存在");
            } else if (userService.insertUserByUsernameAndPassword(username, password) == 1) {
                return Result.ok("注册成功");
            } else {
                return Result.fail("注册失败");
            }
        } else {
            return Result.fail("无效的注册参数");
        }
    }


    @ApiOperation(value = "头像更换", notes = "文件不要超过20M")
    @ApiImplicitParam(name = "request", value = "请求对象", required = true, dataTypeClass = RequestDTO.class)
    @PostMapping("/upload-avatar")
    public Result uploadUserAvatar(@RequestBody RequestDTO request) {
        Long userId = request.getUserId();
        String avatar = request.getBase64Data();
        User user = userService.selectUserByUserId(userId);
        byte[] avatarBytes = null;
        try {
            avatarBytes = Base64.getDecoder().decode(avatar);
        } catch (Exception e) {
            return Result.fail("图片数据格式不正确");
        }
        if (user != null) {
            String avatarUrl = AliOSSUtils.uploadFileToOSS("avatar" + userId + ".jpg", avatarBytes);
            user.setAvatar(avatarUrl);
            return userService.updateUser(user) == 1 ? Result.ok(user) : Result.fail("修改头像失败");
        }
        return Result.fail("用户不存在");
    }

}
